package com.tally.framework.security.utils;

import com.tally.framework.security.dto.LoginUser;
import com.tally.project.system.user.domain.User;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @Author soul
 * @Date 2023/5/19 1:22
 * @Description
 */
public class SecurityUtils {
    /**
     * 获取用户缓存信息
     */
    public static User getUser()
    {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            if (authentication instanceof AnonymousAuthenticationToken) {
                return null;
            }

            if (authentication instanceof UsernamePasswordAuthenticationToken) {
                LoginUser loginUser = (LoginUser) authentication.getPrincipal();
                return loginUser.getUser();
            }
        }
        return null;
    }


    /**
     * 获取登录用户id
     */
    public static Long getUserId()
    {
        return getUser().getUserId();
    }

    /**
     * 获取登录用户名
     */
    public static String getLoginName()
    {
        return getUser().getLoginName();
    }
}
